import storage from '@/utils/storage'
import {
	showLoading
} from './common';

import {
	getMap
} from '@/api/login.js'


export function shouquanweizhi() {
	let aaa = false
	let a = 'scope.userLocation';
	return new Promise((resolve) => {
		try {
			uni.getSetting({
				success(res) {
					console.log(res)
					if (!res.authSetting[a]) {
						//每次进入程序判断当前是否获得授权，如果没有就去获得授权，如果获得授权，就直接获取当前地理位置

						console.log("没有授权位置");

						uni.authorize({
							scope: a,
							success() { //允许授权
								resolve(true);
							},
							fail() {
								uni.showModal({
									title: '授权提示',
									content: '无位置信息,将无法查询最近商家。前往授权页面手动授权',
									success: function(res) {
										if (res.confirm) {
											uni.openSetting({
												success(res) {
													if (res.authSetting[
															a]) {
														resolve(true);
													} else {
														resolve(false);
													}
												}
											})
										}
									}
								})
							}
						})



					} else {
						console.log("已授权位置");
						resolve(false);
					}
				}
			});

		} catch (e) {
			resolve(true);
		}

	});
}
export async function getLocation() {

	await shouquanweizhi()
	return new Promise((resolve) => {
		let that = this;
		showLoading("获取位置中")
		let location = {};
		uni.getLocation({
			type: "gcj02",
			async success(res) {
				location.longitude = res.longitude;
				location.latitude = res.latitude;
				// 腾讯地图Api
				let adf = await getMap2(location)
				console.log(adf)
				uni.hideLoading()
				resolve(adf)
			},
			fail(err) {
				uni.hideLoading()
				reject(err)

			},
		});
	})



}

export async function getMap2(data2) {
	// 腾讯地图Api
	let {
		data
	} = await getMap({
		lon: data2.longitude,
		lat: data2.latitude,
	})
	let asdfasdf = {};
	let info = data.result;
	asdfasdf.province = info.address_component
		.province;
	asdfasdf.city = info.address_component.city;
	asdfasdf.area = info.address_component.district;
	asdfasdf.street = info.address_component.street;
	asdfasdf.address = info.address;
	asdfasdf.longitude = data2.longitude;
	asdfasdf.latitude = data2.latitude;
	storage.setItem("location", asdfasdf)

	return asdfasdf
}